<?php

namespace Admin\Controller;

use Api\Event\OssEvent;

// 视频管理
class VideoController extends BaseManageController 
{

	protected $modelName = 'Common/Video';		// 必须定义
	protected $is_del 	 = false; 		// 是否真实删除

	protected function _initialize()
	{
		parent::_initialize();
		$games = A('Api/Game', 'Event')->lists();
		$model = &$this->model;
		foreach ($games as $key => $value) {
			$this->text_map['game_id'][$value['id']] = $value['name'];
		}
		// $this->text_map['match_id'] = A('Api/Match', 'Event')->options();
		$this->text_map['type'] = array(
			$model::TYPE_NORMAL => '普通',
			$model::TYPE_MATCH  => '赛事',
		);

		$this->text_map['page'] = array(
			$model::PAGE_SINGLE => '单P',
			$model::PAGE_MULTI  => '多P',
		);

		$this->text_map['recommend'] = array(
			$model::RECOMMEND_NO   => '否',
			$model::RECOMMEND_YES  => '推荐',
		);

		$tags = A('Api/Tag', 'Event')->lists('title');
		foreach ($tags as $key => $value) {
			$this->text_map['tags'][$value['title']] = $value['title'];
		}

		$this->assign('options', $this->text_map);
		$this->iconsOptions = A('Api/IconPacks', 'Event')->getIcons(1);
	}

	// 发起转码
	public function transcode($id)
	{
		$video = event('Video')->info($id);
		$transcode = [
			// 1920  1280  960  :  11:9
			// '1080', '720', '540', 
			'360'
		];
		// $video_dpi = $video['dpi'];
		// $transcode = array_filter($transcode, function($var){
		// 	return $video_dpi > $var;
		// });

		if (IS_POST){
			$dpi = I('dpi');
			event('Video')->transeone($video, $dpi);
			// $this->success('已发起, 请等待转码...');
		}else{
			$this->assign($video);
			$this->assign('transcode', $transcode);
			$this->display();
		}
	}


	/**
	*操作index的前置操作
	*---设置数据筛选条件---
	*@author susy.liang <susy.liang@ilongyuan.com.cn>
	*/
	public function _before_index()
	{
		$map = array();
        $map['status']  = array('egt',0);
        $map['type'] = 0;
        $map['race_id'] = array('egt', null);
        I('uid') && $map['uid'] = I('uid', 0, 'intval');
        I('recommend') && $map['recommend'] = I('recommend', 0, 'intval');
        I('tag') && $map['tags'] = I('tag', '', 'trim');
		$search = trim(I('get.title', '', 'strip_tags'));
        if($search){
            $map['title']    =   array('like', (string)$search);
        }
        $this->game = $game = I('get.game', 0, 'intval');
        if($game){
        	$map['game_id'] = $game;
        }
        $this->where = $map;
        $this->gameInfo(true);
	}

	public function format_lists(&$lists)
	{
		foreach ($lists as $key => &$video) {
			$map['match_videos'] = $video['id'];
			$matchVideo = $this->model->where($map)->find();
			if ($matchVideo)
			{
				$video['match_race_id'] = $matchVideo['id'];
			}
		}
	}


	public function _before_edit()
	{
		if (IS_POST)
		{
			if (!I('tags'))
			{
				$_POST['tags'] = array();
			}
			if (!I('icons'))
			{
				$_POST['icons'] = array();
			}
			else
			{
				$_POST['icons'] = array_map('intval', I('icons'));
			}
		}
	}

	public function _after_edit($data)
	{
		$id = I('id', 0, 'intval');
		if ($id) {
			$video = ['id' => $id];
			if (isset($data['status'])) {
				$video['status'] = $data['status'];
			}
			if (isset($data['game_id'])) {
				$video['game_id'] = $data['game_id'];
			}
			event('ResourceGroup')->updateVideo([$video]);
		}
	}

	public function _before_add()
	{
		if (IS_POST)
		{
			if (!I('tags'))
			{
				$_POST['tags'] = array();
			}
			if (!I('icons'))
			{
				$_POST['icons'] = array();
			}
			else
			{
				$_POST['icons'] = array_map('intval', I('icons'));
			}
		}
	}

	public function _after_editRow($id, $data)
	{
		$resources = [];
		if (is_array($id)) {
			foreach ($id as $value) {
				$resources[] = [
					'id' => $value,
					'status' => $data['status']
				];
			}
		} else {
			$resources[] = [
				'id' => $id,
				'status' => $data['status']
			];
		}
		event('ResourceGroup')->updateVideo($resources);
	}

	public function recommend()
	{
		$id = array_unique((array)I('id',0));
        $id = is_array($id) ? array_map('intval',$id) : intval($id);
        $map['id'] =   array('in',$id);
		$model = $this->model;
		$model->where($map)->setField('recommend', $model::RECOMMEND_YES);
		$this->success('操作成功');
	}

	public function undo_recommend()
	{
		$id = array_unique((array)I('id',0));
        $id = is_array($id) ? array_map('intval',$id) : intval($id);
        $map['id'] =   array('in',$id);
		$model = $this->model;
		$model->where($map)->setField('recommend', $model::RECOMMEND_NO);
		$this->success('操作成功');
	}



	// AJAX获取赛事
	public function ajax_get_matches_options()
	{
		$game_id = I('game_id');
		$data = A('Api/Match', 'Event')->options($game_id);
		$this->ajaxReturn($data);
	}

	protected function setGame()
	{
		$this->game = A('Api/Game', 'Event')->lists();
	}

	/**
	*游戏信息获取
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	private function gameInfo($format=false){

		$games = A('Api/Game', 'Event')->lists(array(), 'id,name');

		if($format===false){

			$this->games = $games;

		}else{

			$temp = array();
			foreach ($games as $key => $value) {
				$temp[$value['id']] = $value['name'];
			}

			$this->games = $temp;
		}
	}

	/**
	*设置视频所属栏目
	*@param int $id 视频标识
	*@author susy<susy.liang@ilongyuan.com.cm>
	*/
	public function setTopic($id){
		$id = intval($id);
		if(IS_POST){
			$data = I('');
			$res = $this->model->updateTopic($id, $data);
			if($res===true)
			{
				// 成功后 将选择的首推加入 2015年7月7日14:53:12 Legend.
				$setHome = I('setHome');
				$topics =  I('topics');
				$tService = D('Common/Topic', 'Service');
				foreach ($setHome as $topic_id) {
					if (in_array($topic_id, $topics))
					{
						$map['id'] = intval($topic_id);
						$res = $tService->where($map)->field('videos')->find();
						$videos = explode(',', $res['videos']);
						if (!in_array($id, $videos))
						{
							$videos[] = $id;
							$tService->where($map)->setField('videos', implode(',', $videos));
						}
					}
				}
				$this->success('设置成功');
			}
			
			else
				$this->error('设置失败');
			
		}else{
			$info = $this->model->field('id,title,topics')->find($id);
			if(empty($info))
				$this->error('请选择合法视频项');
			$this->data = $info;
			$topics = D('Common/Topic', 'Service')->lists();
			// 增加显示栏目被选
			foreach ($topics as $key => &$topic) {
				if (in_array($topic['id'], $info['topics']))
				{
					$topic['selected'] = 1;
				}
			}

			$this->topic = $topics;

			$this->display('topic');

		}
	}

	/**
	*设置视频所属的比赛
	*@param int $id 视频标识
	*@author susy<susy.liang@ilongyuan.com.cm>
	*/
	public function setMatch($id){

		$this->id = $id = intval($id);

		if(IS_POST){

			$race_id1 = I('race_id1', 0, 'intval');
			$race_id2 = I('race_id', 0, 'intval');
			$race_id = $race_id2 ? $race_id2 : $race_id1;
			$time = I('time','', 'trim');
			if(!$race_id) $this->error('请选择比赛');
			if(!$time) $this->error('请设置时间结点');
			
			$map['id'] = $race_id;
			$match_video = $this->model->where($map)->find();

			if (in_array($time, $match_video['match_times']))
			{
				$this->error('时间结点重复');
			}

			if (in_array($id, $match_video['match_videos']) )
			{
				$this->error('该视频已经设置在该比赛下');
			}

			$videos = array_combine($match_video['match_times'], $match_video['match_videos']);
			$videos[$time] = $this->id;
			ksort($videos);
			foreach ($videos as $time => $video) {
				$update['match_videos'][] = $video;
				$update['match_times'][] = $time;
			}
			$flg = $this->model->where($map)->save($update);
			$videoUpdate = array('race_id' => $race_id);
			$flg = $this->model->where(array('id'=> $id))->setField($videoUpdate);
			if($flg===false){
				$this->error('操作失败，请联系管理员');
			}else{
				$this->success('操作成功');
			}

		}else{

			$info = $this->model->field('id,title,race_id,game_id')->find($id);
			if(empty($info))
				$this->error('非法视频');

			$this->video = $info;


			$where = array(
				'match_videos' => $id,
			);
			$this->inMatch = $this->model->where($where)->find();
			$map = array(
					'type'=>1,
					'game_id' => $info['game_id'],
					'status'=>array('egt', 0)
				);
			$this->match = $this->model->field('id,title,detail')->order('match_time desc')->where($map)->select();
			$this->display('match');

		}
	}

	// 回收站
	public function trash()
	{
		$lists = $this->getList(service('Video'),['status' => -1]);
		int_to_string($lists, $this->text_map);
		$this->format_lists($lists);
		$this->_list = $lists;
		$this->display();
	}

	// 删除视频源文件
	public function delOssSource($file)
	{
		if (!$file){
			return $this->error('未选择文件');
		}
		OssEvent::delVideo($file);
		$this->success('操作成功');
	}

	public function push($id) {
		$id = intval($id);

		$vService = D('Admin/Video', 'Service');
		$data = $vService->find($id);

		if (empty($data)) {
			$this->error('非法操作项');
		}

		if (IS_POST) {

			$msg = I('msg', '', 'trim');
			if (empty($msg)) {
				$this->error('推送消息不能为空');
			}

			event('Push')->video($id, $msg, $data['game_id']);
			$this->success('推送完成');
		} else {
			$this->assign($data);
			$this->display();
		}

	}


	/** 
	 * [设置精选信息]
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	public function setDailyRecommend($id)
	{
		
	}

}